{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### ICS 104 - Introduction to Programming in Python and C  \n",
    "# Files and Exceptions\n",
    "## Reading Assignment\n",
    "- Chapter 7 Sections 1, 2 and 5."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Chapter Learning Outcomes\n",
    "### At the end of this chapter, you will be able to"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "- read and write text files\n",
    "- process collections of data\n",
    "- raise and handle exceptions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Reading and Writing Text Files\n",
    "## Opening a File for Reading"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "- To access a <font color='blue'>**file**</font>, you must first <font color='blue'>**open**</font> it.\n",
    "- When you open a file, you give the name of the file.\n",
    "    - If the  file is stored in a different directory, the file name is preceded by the directory path. \n",
    "- You also specify whether the file is to be opened for <font color='blue'>**reading**</font> or <font color='blue'>**writing**</font>. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "infile = open(\"input.txt\",\"r\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- This statement opens the file for reading (indicated by the string argument <font color='blue'>**\"r\"**</font>) and returns a file <font color='blue'>**object**</font> that is associated with the file <font color='blue'>**input.txt**</font>.\n",
    "    - Stores the file object in a variable <font color='blue'>**infile**</font>\n",
    "- When opening a file for reading, the file must <font color='blue'>**exist**</font> or an <font color='blue'>**exception**</font> is raised."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Opening a File for Writing\n",
    "- To open a file for writing, use the following statement"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "outfile = open(\"output.txt\",\"w\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- If the output file already exists, it is emptied before the new data is written into it. \n",
    "- If the file does not exist, an empty file is created."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- All operations for accessing a file are made via the file object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- When you are done processing a file, by sure to close the file using the close method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "infile.close()\n",
    "outfile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- If your program exits without closing a file that was opened for writing, some of the output may not be written to the file."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Reading and Writing Text Files"
   ]
  },
  {
   "attachments": {
    "ch07fig1.PNG": {
     "image/png": "[encoded data, 102328 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "![ch07fig1.PNG](attachment:ch07fig1.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Reading a File"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- To read a line of text from a file, call the <font color='blue'>**readline()**</font> method on the file object that was returned when you opened the file."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- When a file is opened, an input marker is positioned at the beginning of the file.\n",
    "- The <font color='blue'>**readline**</font> method reads the text, starting at the current position and continuing until the newline character is encountered."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- The input marker is then moved to the next line.\n",
    "- The <font color='blue'>**readline**</font> method returns the text that it reads, including the newline character that denotes the end of the line.\n",
    "    - Consider the input file \"input.txt\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "# A sample use of readline\n",
    "infile = open(\"input.txt\",\"r\")\n",
    "line1 = infile.readline()\n",
    "print(line1 + \"The length of line1 is\", len(line1))\n",
    "line2 = infile.readline()\n",
    "print(line2 + \"The length of line2 is\", len(line2))\n",
    "line3 = infile.readline()\n",
    "print(line3 + \"The length of line3 is\", len(line3))\n",
    "infile.close() "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- The first call to <font color='blue'>**readline**</font> returns the string \"flying\\n\". \n",
    "    - Recall that \\n denotes the newline character that indicates the end of the line. \n",
    "- If you call <font color='blue'>**readline**</font> a second time, it returns the string \"circus\".\n",
    "    - Note that there is no \"\\n\" since this was the last line in the text file, and you have reached the end of file marker.\n",
    "- Calling <font color='blue'>**readline**</font> again yields the empty string \"\" because you have already reached the end of file marker."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Reading Multiple Lines of a File"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Reading multiple lines of text from a file is very similar to reading a sequence of values with the input function. \n",
    "- You repeatedly read a line of text and process it until the sentinel value is reached:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "infile = open(\"input.txt\",\"r\")\n",
    "line = infile.readline()\n",
    "print(line, end=\"\")\n",
    "while line !=\"\" :\n",
    "    line = infile.readline()\n",
    "    print(line, end=\"\")\n",
    "print()\n",
    "infile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- As with the <font color='blue'>**input**</font> function, the <font color='blue'>**readline**</font> method can return only strings. \n",
    "- If the file contains numerical data, the strings must be converted to the numerical value using the `int` or `float` function:\n",
    "    - For example, \"`value = float(line)`\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Writing a File"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- You can write text to a file that has been opened for writing. \n",
    "- This is done b applying the <font color='blue'>**write()**</font> method to the file object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- For example, we can write the string \"Hello, World\" to our output file using the statement:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "outfile = open(\"output.txt\",\"w\")\n",
    "outfile.write(\"Hello, World!\\n\")\n",
    "outfile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## A File Processing Example"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Suppose you are given a text file that contains a sequence of floating-point values, stored one value per line. \n",
    "- You need to read the values and write them to a new output file, aligned in a column and followed by their total and average values. "
   ]
  },
  {
   "attachments": {
    "ch07fig2.PNG": {
     "image/png": "[encoded data, 30644 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- If the input file has the content: \n",
    "![ch07fig2.PNG](attachment:ch07fig2.PNG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "#  This program reads a file containing numbers and writes the numbers to another file, lined up in a column and followed by their total and average.\n",
    "# Prompt the user for the name of the input and output files.\n",
    "inputFileName = input(\"Input file name: \")       # Use input1.txt\n",
    "outputFileName = input(\"Output file name: \")     # Use output1.txt \n",
    "# Open the input and output files.\n",
    "infile = open(inputFileName, \"r\")\n",
    "outfile = open(outputFileName, \"w\")\n",
    "# Read the input and write the output.\n",
    "total = 0.0\n",
    "count = 0\n",
    "line = infile.readline()\n",
    "while line != \"\" :\n",
    "    value = float(line)\n",
    "    outfile.write(\"%15.2f\\n\" % value)\n",
    "    total = total + value\n",
    "    count = count + 1\n",
    "    line = infile.readline()\n",
    "# Output the total and average.\n",
    "outfile.write(\"%15s\\n\" % \"--------\")\n",
    "outfile.write(\"Total: %8.2f\\n\" % total)\n",
    "\n",
    "avg = total / count\n",
    "outfile.write(\"Average: %6.2f\\n\" % avg)\n",
    "# Close the files.\n",
    "infile.close()\n",
    "outfile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Iterating over the Lines of a File"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- To read the lines of text from the file, you can iterate over the file object using a <font color='blue'>**for**</font> loop. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "infile = open(\"input.txt\",\"r\")\n",
    "for line in infile:\n",
    "    print(line)\n",
    "infile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Note, when the lines of input are printed to the terminal, they are displayed with a blank line between each word:\n",
    "- To remove the newline character, apply the <font color='blue'>**rstrip**</font> method to the string.\n",
    "    - The `rstrip()` method removes all trailing white spaces (tabs, spaces and newlines) from the end of the string when called without an argument.\n",
    "        - If we supply an argument, it will remove the trailing characters in the argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "infile = open(\"input.txt\",\"r\")\n",
    "for line in infile:\n",
    "    line = line.rstrip() \n",
    "    print(line)\n",
    "infile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Reading Words"
   ]
  },
  {
   "attachments": {
    "ch07fig3.PNG": {
     "image/png": "[encoded data, 10288 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Sometimes you may need to read the individual words from a text file. \n",
    "- For example, suppose our input file contains two lines of text\n",
    "![ch07fig3.PNG](attachment:ch07fig3.PNG)"
   ]
  },
  {
   "attachments": {
    "ch07fig4.PNG": {
     "image/png": "[encoded data, 4268 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "- that we would like to print to the terminal, one word per line\n",
    "![ch07fig4.PNG](attachment:ch07fig4.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- There is no method for reading a word from a file, you must first read a line and then split it into individual words. \n",
    "- This can be done using the `split()` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<_io.TextIOWrapper name='7.2.2.txt' mode='r' encoding='cp1252'>\n",
      "['Mary', 'had', 'a', 'little', 'lamb,']\n",
      "['whose', 'fleece', 'was', 'white', 'as', 'snow.']\n"
     ]
    }
   ],
   "source": [
    "infile = open(\"7.2.2.txt\",\"r\")\n",
    "for line in infile:\n",
    "    wordList = line.split()\n",
    "    print(wordList)\n",
    "infile.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "infile = open(\"7.2.2.txt\",\"r\")\n",
    "for line in infile:\n",
    "    wordList = line.split()\n",
    "    for word in wordList:\n",
    "        print(word)\n",
    "infile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Reading Words - Student Activity"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Notice that the last word in the last output contains punctuation marks. \n",
    "- If you want to print the words contained in the file without punctuation marks, which function we can use?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "infile = open(\"7.2.2.txt\",\"r\")\n",
    "for line in infile:\n",
    "    wordList = line.split()\n",
    "    for word in wordList:\n",
    "        word = word.rstrip(\".,?!\")\n",
    "        print(word)\n",
    "infile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Reading Characters "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Instead of reading an entire line, you can read individual characters with the <font color='blue'>**read**</font> method. \n",
    "- The <font color='blue'>**read**</font> method takes a single argument that specifies the number of characters to read. \n",
    "- The method returns a string containing the characters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- When supplied with an argument of 1,\n",
    "    - char = inputFile.read(1)\n",
    "- the read method returns a string consisting of the next character in the file. \n",
    "- Or, if the end of the file is reached, it returns an empty string \"\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "inputFile = open(\"input.txt\",\"r\")\n",
    "char = inputFile.read(1)\n",
    "while char !=\"\":\n",
    "    char = inputFile.read(1)\n",
    "    print(char)\n",
    "inputFile.close() "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Reading Records "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- A text file can contain a collection of <font color='blue'>**data records**</font> in which each record consists of multiple fields. \n",
    "- For example, a file containing student data may consist of records composed of fields for an identification number, full name, address, and class year. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- A file containing bank account transactions may contain records composed of the transaction date, description, and amount fields. \n",
    "- When working with text files that contain data records, you generally have to read the entire record before you can process it:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- For each record in file\n",
    "    - Read the entire record.\n",
    "    - Process the record. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Exception Handling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- There are two aspects to dealing with program errors: detection and handling. \n",
    "- For example, the `open()` function can detect an attempt to read from a non-existent file.\n",
    "    - However, it cannot handle that error. \n",
    "    - A satisfactory way of handling the error might be to terminate the program, or to ask the user for another file name. \n",
    "    - The `open()` function cannot choose between the alternatives.\n",
    "    - It needs to report the error to another part of the program."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- In Python, <font color='blue'>**exception handling**</font> provides a flexible mechanism for passing control from the point of <font color='blue'>**error**</font> detection to a handler that can deal with the error. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Raising Exceptions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- When you detect an error condition, your job is really easy. \n",
    "- You just <font color='blue'>**raise**</font> an appropriate exception, and you are done."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- For example, suppose someone tries to withdraw too much money from a bank account:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "# if amount > balance:\n",
    "    # Now what?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- First look for an appropriate exception. \n",
    "- The Python library provides a number of standard exceptions to signal all sorts of exceptional conditions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Standard Exceptions"
   ]
  },
  {
   "attachments": {
    "ch07fig5.PNG": {
     "image/png": "[encoded data, 46376 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch07fig5.PNG](attachment:ch07fig5.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Look around for an exception type that might describe your situation?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "- How about the ArithematicError exception? Is it an arithmetic error to have a negative balance?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- No, Python can deal with negative numbers."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Is the amount to be withdrawn an illegal value?\n",
    "    - Indeed it is. It is just too large. \n",
    "    - Therefore, let's raise a ValueError exception."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "amount = 100\n",
    "balance = 50\n",
    "if amount > balance:\n",
    "    raise ValueError(\"Amount exceeds balance\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Raising Exceptions"
   ]
  },
  {
   "attachments": {
    "ch07fig6.PNG": {
     "image/png": "[encoded data, 83740 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch07fig6.PNG](attachment:ch07fig6.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- When you raise an exception, execution does not continue with the next statement but with an *exception handler*. \n",
    "    - Every exception should be handled somewhere in your program. \n",
    "    - If an exception has no handler, an error message is printed, and your program terminates."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Handling Exceptions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- You handle exceptions with the <font color='blue'>**try/except**</font> statement. \n",
    "- Place the statement into a location of your program that knows how to handle a particular exception. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- The <font color='blue'>**try block**</font> contains one or more statements that may cause an exception of the kind that you are willing to handle. \n",
    "- Each except clause contains the handler for an exception type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    filename= input(\"Enter filename: \")\n",
    "    infile = open(filename, \"r\")\n",
    "    line = infile.readline()\n",
    "    value = int(line)\n",
    "except IOError:\n",
    "    print(\"Error: file not found\")\n",
    "except ValueError as exception:\n",
    "    print(\"Error:\",str(exception)) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## General Syntax for Handling Exceptions"
   ]
  },
  {
   "attachments": {
    "ch07fig7.PNG": {
     "image/png": "[encoded data, 111852 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch07fig7.PNG](attachment:ch07fig7.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## The Finally Clause"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Occasionally, you need to take some action whether or not an exception is raised. \n",
    "- The <font color='blue'>**finally**</font> construct is used to handle this situation."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- For example, it is important to close an output file to ensure that all output is written to the file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "filename= input(\"Enter filename: \")\n",
    "outfile = open(filename, \"w\")\n",
    "try:\n",
    "    outfile.write(\"Hello World\\n\")\n",
    "    value = 1 / 0 \n",
    "    outfile.close()\n",
    "except ArithmeticError as exception:\n",
    "    print(\"Error:\",str(exception)) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Since <font color='blue'>**ArithmeticError**</font> exception is raised, the call to close is never executed. \n",
    "- You solve this problem by placing the call to <font color='blue'>**close**</font> inside a <font color='blue'>**finally clause**</font>:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "filename= input(\"Enter filename: \")\n",
    "outfile = open(filename, \"w\")\n",
    "try:\n",
    "    outfile.write(\"Hello World\\n\")\n",
    "    value = 1 / 0 \n",
    "except ArithmeticError as exception:\n",
    "    print(\"Error:\",str(exception)) \n",
    "finally:\n",
    "    outfile.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Syntax of the Finally Clause"
   ]
  },
  {
   "attachments": {
    "ch07fig8.PNG": {
     "image/png": "[encoded data, 106620 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch07fig8.PNG](attachment:ch07fig8.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- The `finally` block is always executed after leaving the try statement. \n",
    "- In case if some exception was not handled by except block, it is re-raised after execution of finally block.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Summary\n",
    "- When opening a file, you supply the name of the file stored on disk and the mode in which the file is to be opened.\n",
    "- Close all files when you are done processing them.\n",
    "- Use the readline() method to obtain lines of text from a file.\n",
    "- Write to a file using the write() method or the pring() function. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Summary\n",
    "- You can iterate over a file object to read the lines of text in the file.\n",
    "- Use the rstrip() method to remove the newline character from a line  of text.\n",
    "- Use the split() method to split a string into individual words.\n",
    "- Read one or more characters with the read() method. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Summary\n",
    "- To signal an exception condition, use the `raise` statement to raise an exception object. \n",
    "- When you raise an exception, processing continues in an exception handler. \n",
    "- Place the statements that can cause an exception inside a try block, and the handler inside an except clause.\n",
    "- Once a try block is entered, the statements in a finally clause are guaranteed to be executed, whether or not an exception is raised. "
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "rise": {
   "theme": "yellow"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
